import { $get } from "@src/assets/js/request"

// 获取最新组庭信息
export async function getCourtRequest (caseid, caseDetail, uid) {
  const res = await $get('/api/xd/tribunal/getPartyTribunal', { caseid })
  const list = res.data
  if (list.length > 0) {
    return list
  }
  const oList = await getAllCourtRequest(caseid)
  if (oList.length === 0) {
    return []
  }
  oList.sort((a, b) => b.create_datetime - a.create_datetime)
  return formatPartyList(oList, caseDetail, uid)
}

// 获取案件全部组庭信息
export async function getAllCourtRequest (caseid) {
  const res = await $get('/api/xd/tribunal', { caseid })
  return res.data
}

function formatPartyList (list, caseDetail, uid) {
  const o = list[0]
  const partys = [...caseDetail.applicants, ...caseDetail.respondents]
  const agents = [...caseDetail.applicant_agents, ...caseDetail.respondents_agents]
  let index = partys.map(li => li.accountid).indexOf(uid)
  let ids = []
  if (index !== -1) {
    ids.push(partys[index].id)
  } else {
    index = agents.map(li => li.accountid).indexOf(uid)
    if (index !== -1) {
      ids = agents[index].party.map(li => li.partyid)
    }
  }
  const result = o.tribunal_party.filter(li => ids.includes(li.partyid))
  result.forEach(li => {
    li.tribunal_arbitrator = o.arbitrator
    li.tribunal_arbitrator1 = o.arbitrator1
    li.tribunal_arbitrator2 = o.arbitrator2
    li.tribunal_arbitratorid = o.arbitratorid
    li.tribunal_arbitratorid1 = o.arbitratorid1
    li.tribunal_arbitratorid2 = o.arbitratorid2
    li.tribunal_status = o.status
    li.tribunal_assign_datetime = o.assign_datetime
  })
  return result
}

